/*
 * @Author: fanjs
 * @Date: 2025-01-08 00:03:50
 * @Description: 
 */
import Router, { IMiddleware, RouterContext } from 'koa-router'
import { Next } from 'koa'
import { verifyToken } from '@core/util'
import { isInScope } from '@app/lib/scope'

export default class Auth {
  // 设置属性
  private static ctx: RouterContext
  private static routerName: string

  /**
   * 权限校验
   * @param {String} routerName 视图函数的名称
   * @returns
   */
  static get verify() {
    return (routerName: string) => {
      return async (ctx: RouterContext, next: Next) => {
        this.ctx = ctx
        this.routerName = routerName

        // 从 Authorization 头获取 token
        const bearerToken = ctx.request.header.authorization
        if (!bearerToken) throw new global.errs.Forbidden('token不存在')

        // 移除 "Bearer " 前缀
        const token = bearerToken.replace('Bearer ', '')
        const { uid, scope, nickname } = verifyToken(token)
        if (!isInScope(scope, this.endpoint)) {
          throw new global.errs.Forbidden('权限不足')
        }

        // 直接使用 token 中的用户信息
        (ctx as any).auth = { uid, scope, nickname }
        await next()
      }
    }
  }

  /**
   * 视图函数的唯一标识: {路由版本}.{路由类别}+{函数名}
   *             E.g: v1.classic+getLatest
   *
   * @returns
   */
  static get endpoint() {
    // 去除全局前缀 apiPrefix 
    const [, _apiPrefix, routerVersion, routerCategory] = this.ctx.url.split('/')
    return `${routerVersion}.${routerCategory}+${this.routerName}`
  }
}
